package com.du.service.impl;

import com.du.constants.SsmConstans;
import com.du.domain.User;
import com.du.enums.ExceptionEnum;
import com.du.exception.SsmException;
import com.du.mapper.UserMapper;
import com.du.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void checkUserName(String username) {
        //封装查询条件
        User param = new User();
        param.setUsername(username);
        //执行查询
        int count = userMapper.selectCount(param);
        //判断返回结果
        if (count!=0){
            //用户名已存在
            //记录日志
            log.error("【异步校验用户名】 用户名已存在 username={}",username );
            //抛出自定义异常
            throw new SsmException(ExceptionEnum.CHECK_USERNAME);
        }
    }

    @Override
    public void register(User user) {
        //1. 生成一个盐
        String salt = UUID.randomUUID().toString();
        //2. 对密码进行md5加密和加盐.	->shiro-core-1.4.0
        String newPassword = new Md5Hash(user.getPassword(), salt, SsmConstans.HASH_ITERATIONS).toString();
        //3. 封装数据.
        user.setSalt(salt);
        user.setPassword(newPassword);
        //4. 执行添加.
        int count = userMapper.insertSelective(user);
        //5. 判断注册是否成功.
        if (count!=1){
            log.error("【用户注册】 注册失败！！user={}", user);
            throw new SsmException(ExceptionEnum.REGISTER_FAILURE);
        }
    }

    //登录
    @Override
    public User loginCheck(String username,String password) {
        //  0. 封装数据
        User user = new User();
        user.setUsername(username);
        //	1. 根据用户名查询用户信息.
        User checkUser = userMapper.selectOne(user);
        //	2. 如果用户信息为null -> 用户名不正确.
        if (checkUser==null){
            log.error("【用户登录】 登录失败！用户名不存在！user={}", user);
            throw new SsmException(ExceptionEnum.USERNAME_NOT_EXIST);
        }
        //	3. 将用户输入的密码进行加密和加盐.
        user.setPassword(new Md5Hash(password,checkUser.getSalt(),SsmConstans.HASH_ITERATIONS).toString());
        //	4. 判断密码是否正确(不正确) -> 密码不正确.
        if (!user.getPassword().equals(checkUser.getPassword())){
            log.error("【用户登录】 登录失败！密码错误！user={}", user);
            throw new SsmException(ExceptionEnum.PASSWORD_ERROR);
        }
        //  5. 返回用户信息.
        return user;
    }
}
